import axios from 'axios'
import { ElMessage } from 'element-plus'
import router from '../router'

// 创建axios实例
const request = axios.create({
  baseURL: 'http://localhost:8000', // Django后端地址
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 是否正在刷新token
let isRefreshing = false
// 重试队列
let requests = []

// 刷新token
const refreshToken = async () => {
  try {
    const refresh_token = localStorage.getItem('refresh_token')
    if (!refresh_token) {
      throw new Error('No refresh token')
    }
    const response = await axios.post('http://localhost:8000/api/token/refresh/', {
      refresh: refresh_token
    })
    const { access } = response.data
    localStorage.setItem('access_token', access)
    return access
  } catch (error) {
    localStorage.clear()
    router.push('/login')
    throw error
  }
}

// 请求拦截器
request.interceptors.request.use(
  config => {
    // 从localStorage获取token
    const tokenData = localStorage.getItem('token')
    if (tokenData) {
      try {
        const token = JSON.parse(tokenData)
        if (token.access && !config.url.includes('login') && !config.url.includes('register')) {
          config.headers.Authorization = `Bearer ${token.access}`
        }
      } catch (e) {
        console.error('Token解析错误:', e)
        localStorage.removeItem('token')
        router.push('/login')
      }
    }
    return config
  },
  error => {
    console.error('请求错误:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => {
    // 如果是登录接口，保存token
    if (response.config.url.includes('login')) {
      const tokenData = response.data.token
      localStorage.setItem('token', JSON.stringify(tokenData))
    }
    return response.data
  },
  async error => {
    const originalRequest = error.config

    // 打印详细错误信息
    console.error('请求错误详情:', {
      url: originalRequest?.url,
      method: originalRequest?.method,
      status: error.response?.status,
      data: error.response?.data,
      error: error.message
    })

    // 处理401错误（未授权）
    if (error.response?.status === 401 && !originalRequest._retry) {
      if (isRefreshing) {
        return new Promise(resolve => {
          requests.push(token => {
            originalRequest.headers.Authorization = `Bearer ${token}`
            resolve(request(originalRequest))
          })
        })
      }

      originalRequest._retry = true
      isRefreshing = true

      try {
        const tokenData = JSON.parse(localStorage.getItem('token'))
        const refresh_token = tokenData?.refresh
        if (!refresh_token) {
          throw new Error('No refresh token')
        }
        
        const response = await axios.post('http://localhost:8000/api/token/refresh/', {
          refresh: refresh_token
        })
        
        const { access } = response.data
        const newTokenData = { ...tokenData, access }
        localStorage.setItem('token', JSON.stringify(newTokenData))
        
        requests.forEach(cb => cb(access))
        requests = []
        originalRequest.headers.Authorization = `Bearer ${access}`
        return request(originalRequest)
      } catch (refreshError) {
        console.error('Token刷新失败:', refreshError)
        localStorage.clear()
        router.push('/login')
        return Promise.reject(refreshError)
      } finally {
        isRefreshing = false
      }
    }

    // 错误处理
    const errorMsg = error.response?.data?.message || error.response?.data?.detail || error.message || '请求失败'
    
    switch (error.response?.status) {
      case 400:
        ElMessage.error(`请求参数错误: ${errorMsg}`)
        break
      case 403:
        ElMessage.error(`权限不足: ${errorMsg}`)
        break
      case 404:
        ElMessage.error(`资源不存在: ${errorMsg}`)
        break
      case 500:
        ElMessage.error(`服务器错误: ${errorMsg}`)
        break
      default:
        if (error.message.includes('Network Error')) {
          ElMessage.error('网络连接失败，请检查网络')
        } else if (error.message.includes('timeout')) {
          ElMessage.error('请求超时，请重试')
        } else {
          ElMessage.error(errorMsg)
        }
    }
    return Promise.reject(error)
  }
)

export default request